package com.dongnam.quanly.common.controller;

import java.util.List;

import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.dao.DoiTacDao;
import com.dongnam.quanly.common.dao.NhanVienDao;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.DoiTac;
import com.dongnam.quanly.common.model.NhanVien;
import com.dongnam.quanly.common.persistence.HibernateUtil;

public class DoiTacController extends GenericController<DoiTac, String> {

	public DoiTacController() {
		super(new DoiTacDao());
		// TODO Auto-generated constructor stub
	}

	@Override
	public DoiTacDao getDao() {
		// TODO Auto-generated method stub
		return (DoiTacDao) dao;
	}

	private static final Logger logger = LoggerFactory.getLogger(DoiTacController.class);

	public long findCountByFilters() throws DatabaseException {
		boolean isTransacted = HibernateUtil.getCurrentSession().getTransaction().isActive();
		Session session = isTransacted ? HibernateUtil.getCurrentSession() : HibernateUtil.startCurrentSession();
		long count;
		try {
			count = getDao().findCountByFilters();
			if (!isTransacted) {
				session.getTransaction().commit();
			}
		} catch (Throwable e) {
			rollbackConditionally(isTransacted, session);
			logger.debug("exception", e);
			throw new DatabaseException(e);
		}
		return count;

	}

	public List<DoiTac> findByFilters(int pageSize, int pageNumber, String sortOrder, String sortField)
			throws DatabaseException {
		logger.debug("findByFilters, pageSize: " + pageSize);
		boolean isTransacted = HibernateUtil.getCurrentSession().getTransaction().isActive();
		Session session = isTransacted ? HibernateUtil.getCurrentSession() : HibernateUtil.startCurrentSession();

		try {
			logger.debug("load (pageSize = {}, sortField = {}, sortOrder = {})", new Object[] { pageSize, sortField,
					sortOrder });
			List<DoiTac> list = getDao().findByFilters(pageSize, pageNumber, sortField, sortOrder);

			if (!isTransacted) {
				session.getTransaction().commit();
			}
			return list;
		} catch (Throwable e) {
			rollbackConditionally(isTransacted, session);
			logger.debug("exception", e);
			throw new DatabaseException(e);
		}

	}

}
